﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace DotNet.Utilities.数据转换类
{
    public class ToDataTable
    {
        #region List转Table
        /// <summary>
        /// 将List转换为DataTable
        /// </summary>
        /// <param name="list">请求数据</param>
        /// <returns></returns>
        public static DataTable ListToDataTable<T>(List<T> list)
        {
            //创建一个名为"tableName"的空表
            DataTable dt = new DataTable("tableName");
            //创建传入对象名称的列
            foreach (var item in list.FirstOrDefault().GetType().GetProperties())
            {
                dt.Columns.Add(item.Name);
            }
            //循环存储
            foreach (var item in list)
            {
                //新加行
                DataRow value = dt.NewRow();
                //根据DataTable中的值，进行对应的赋值
                foreach (DataColumn dtColumn in dt.Columns)
                {
                    int i = dt.Columns.IndexOf(dtColumn);
                    //基元元素，直接复制，对象类型等，进行序列化
                    if (value.GetType().IsPrimitive)
                    {
                        value[i] = item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item);
                    }
                    else
                    {
                        value[i] = JsonConvert.SerializeObject(item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item));
                    }
                }
                dt.Rows.Add(value);
            }
            return dt;
        }
        #endregion
        #region dic转Table
        /// <summary>
        /// Dictionary转datatable
        /// </summary>
        /// <param name="dicDep"></param>
        /// <returns></returns>
        public static DataTable DicToTable(Dictionary<string, Dictionary<string, int>> dicDep)
        {
            DataTable dt = new DataTable();
            //添加列
            dt.Columns.Add("SDDate", typeof(string));
            dt.Columns.Add("SDAcceptance", typeof(int));
            dt.Columns.Add("SDDelivery", typeof(int));
            //添加值
            foreach (KeyValuePair<string, Dictionary<string, int>> item in dicDep)
            {
                DataRow dr = dt.NewRow();
                dr["SDDate"] = item.Key;
                dr["SDAcceptance"] = item.Value["atnum"];
                dr["SDDelivery"] = item.Value["dvnum"];
                dt.Rows.Add(dr);
            }
            return dt;
        }
    }
    #endregion
}
